package com.insyte.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.media.tv.TvInputService;
import android.os.Bundle;
import android.os.Handler;
import android.service.textservice.SpellCheckerService;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.gson.Gson;
import com.insyte.R;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.config.InsyteEnums;
import com.insyte.model.Category;
import com.insyte.model.CategoryOfInterest;
import com.insyte.model.FacebookData;
import com.insyte.model.InteresetObject;
import com.insyte.model.Paging;
import com.insyte.model.User;
import com.insyte.utils.Initialize;
import com.insyte.utils.MultipleScreen;
import com.insyte.utils.ParserFaceBookUntils;
import com.insyte.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class WelcomeActivity extends ActionBarActivity implements View.OnClickListener {

    private RelativeLayout btn_login_email, btn_login_facebook, btn_login_phone;
    private CallbackManager callbackManager;
    LoginButton loginButton;
    private Initialize initialize;
    private ProgressDialog progressDialog;
    private User user;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private AQuery aQuery;
    private Map<String, Object> params;
    String url_login_facebook = Constants.URL_API + "/auth/facebook/token";
    private static final List<String> PERMISSIONS = Arrays.asList("user_likes");//"publish_actions"
    private Map<String, List<InteresetObject>> list_like_of_cate;
    private List<Category> list_InterestFB = new ArrayList<>();
    private List<InteresetObject> list_like = new ArrayList<>();
    private List<Map<String, List<InteresetObject>>> list_category_fb;
    String[] list_read = new String[]{"email",};
    String interest = "";
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aQuery = new AQuery(this);
        prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
        editor = prefs.edit();
        params = new HashMap<String, Object>();
        initialize = new Initialize(this);
        progressDialog = initialize.createProgressDialog("Loading");
        FacebookSdk.sdkInitialize(this);
        callbackManager = CallbackManager.Factory.create();
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.insyte",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
        user = InsyteApp.getInstance().getUser();
        setContentView(R.layout.activity_welcome);
        Constants.fScale = MultipleScreen.getScale(this);
        getView();

        //loginButton.setReadPermissions("publish_stream");

        loginButton.setReadPermissions("publish_stream");

        loginButton.setReadPermissions(PERMISSIONS);
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
               Set<String> permissions = AccessToken.getCurrentAccessToken().getPermissions();
                //TODO: success go to main
                Log.e("AccessToken:", loginResult.getAccessToken().getToken().toString());
                Log.e("UserFBId:", loginResult.getAccessToken().getUserId().toString());
                InsyteApp.getInstance().saveFacebookToken(prefs, loginResult.getAccessToken().getToken().toString());
                progressDialog = new ProgressDialog(WelcomeActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setCanceledOnTouchOutside(false);
                if (!progressDialog.isShowing())
                    progressDialog.show();
                InsyteApp.setTypeLoginEnum(WelcomeActivity.this, InsyteEnums.TypeLogin.FB);
                registerWithFacebookToken(loginResult.getAccessToken().getToken().toString());
                new GraphRequest(AccessToken.getCurrentAccessToken(),
                        "/" + AccessToken.getCurrentAccessToken().getUserId() + "/likes",
                        null,HttpMethod.GET,
                        new GraphRequest.Callback() {
                            public void onCompleted(GraphResponse response) {
                                try {
                                    final String resp = response.getRawResponse();
                                    Log.e("response is: ", "" + resp);
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            parseDataFb(resp);
                                        }
                                    },3000);
                                } catch (Exception e) {
                                    Toast.makeText(WelcomeActivity.this, "error is: " + e.toString(), Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                ).executeAsync();
            }

            @Override
            public void onCancel() {
                ToastUtils.showToast(WelcomeActivity.this, "User canceled.");
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Log.e("", exception.getMessage());
                ToastUtils.showToast(WelcomeActivity.this, "Error: " + exception.getMessage());
            }
        });
        setEvent();
    }

    private void getView() {
        btn_login_email = (RelativeLayout) findViewById(R.id.btn_login_email);
        btn_login_facebook = (RelativeLayout) findViewById(R.id.btn_login_facebook);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        btn_login_phone = (RelativeLayout) findViewById(R.id.btn_login_phone);
    }

    private void setEvent() {
        btn_login_email.setOnClickListener(this);
        btn_login_facebook.setOnClickListener(this);
        btn_login_phone.setOnClickListener(this);
    }

    private void registerWithFacebookToken(String tokenFB) {
        params = new HashMap<String, Object>();
        initialize = new Initialize(this);
        params.put("access_token", tokenFB);
        aQuery.ajax(url_login_facebook, params, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                progressDialog.dismiss();
                if (result != null) {
                    try {
                        JSONObject js = new JSONObject(result);
                        if (js.has("code")) {
                            if (js.getInt("code") == 1) {
                                Gson gson = new Gson();
                                String jsData = js.getString("data");
                                //user = new User();
                                user = gson.fromJson(jsData, User.class);
                                Log.e("uId", js.getString("message"));
                                //TODO save user to global or put intent
                                InsyteApp.getInstance().saveUser(user);
                                //user.saveUserInformation(prefs);
                                startActivity(new Intent(WelcomeActivity.this, ProfileActivity.class));
                            }
                            finish();
                        }
                        Log.d("",js.getString("message"));
                        //initialize.showToast(js.getString("message"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    initialize.showToast("check server");
                }
            }
        }.method(AQuery.METHOD_POST).header("Content-Type", "application/x-www-form-urlencoded"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login_email:
                InsyteApp.setTypeLoginEnum(WelcomeActivity.this, InsyteEnums.TypeLogin.EMAIL);
                startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
                break;
            case R.id.btn_login_facebook:
                if (initialize.checkNetwork()) {
                    InsyteApp.setTypeLoginEnum(WelcomeActivity.this, InsyteEnums.TypeLogin.FB);
                    loginButton.performClick();
                    //startActivity(new Intent(WelcomeActivity.this, ProfileActivity.class));
                } else {
                    initialize.showToast("Please check your network!");
                }
                break;
            case R.id.btn_login_phone:
                InsyteApp.setTypeLoginEnum(WelcomeActivity.this, InsyteEnums.TypeLogin.PHONE);
                startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    public void parseDataFb(String response) {
                if (response != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        FacebookData facebookData = ParserFaceBookUntils.facebookData(jsonObject);
                        List<Category> categories = facebookData.getCategories();
                        Paging paging = facebookData.getPaging();
                        String next = paging.getNext();
                        String befor = paging.getCursors().getBefore();
                        String alter = paging.getCursors().getAfter();
                        if (list_InterestFB.size() > 0) list_InterestFB.clear();
                        list_InterestFB.addAll(categories);
                        if (list_InterestFB.size() > 0) {
                            for (int i = 0; i < list_InterestFB.size(); i++) {
                                if (i == list_InterestFB.size() - 1)
                                    interest = interest + "," + list_InterestFB.get(i).getName();
                                else if (i == 0) {
                                    interest = list_InterestFB.get(i).getName();
                                } else interest = interest + "," + list_InterestFB.get(i).getName();
                            }
                        }
                        user.setLsInterestFB(list_InterestFB);
                        user.setInterest(interest);
                        InsyteApp.getInstance().saveUser(user);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    initialize.showToast("facebook likes is null");
                }
            }

//    private void parseDataFb(String data) {
//        try {
//            //TODO get list category and list favour
//            JSONObject js = new JSONObject(data);
//            list_like_of_cate = new HashMap<String, List<InteresetObject>>();
//            if (js.has("data") && js.getJSONArray("data").length() > 0) {
//                for (int i = 0; i < js.getJSONArray("data").length(); i++) {
//                    JSONObject jsonObject = js.getJSONArray("data").getJSONObject(i);
//                    InteresetObject interesetObject = new InteresetObject();
//                    interesetObject.setName(jsonObject.getString("name"));
//                    if (!list_like_of_cate.containsKey(jsonObject.getString("category"))) {
//                        List<InteresetObject> new_list_like = new ArrayList<InteresetObject>();
//                        new_list_like.add(interesetObject);
//                        list_like_of_cate.put(jsonObject.getString("category"), new_list_like);
//                    } else {
//                        List<InteresetObject> list_like_added = list_like_of_cate.get(jsonObject.getString("category"));
//                        list_like_added.add(interesetObject);
//                        list_like_of_cate.remove(jsonObject.getString("category"));
//                        list_like_of_cate.put(jsonObject.getString("category"), list_like_added);
//                    }
//                }
//            } else {
//
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }
}
